package com.hjxr.quota.datasource.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.api.R;
import com.hjxr.framework.aspectj.lang.annotation.Log;
import com.hjxr.framework.aspectj.lang.enums.BusinessType;
import com.hjxr.quota.datasource.domain.ColnameAlias;
import com.hjxr.quota.datasource.domain.QuotaDimension;
import com.hjxr.quota.datasource.domain.QuotaDimensionDetail;
import com.hjxr.quota.datasource.domain.TablenameAlias;
import com.hjxr.quota.datasource.domain.vo.DimensionVo;
import com.hjxr.quota.datasource.service.*;
import com.hjxr.quota.datasource.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

/**
 * 维度编码详细 前端控制器
 *
 * @author sun
 * @since 2020-09-17
 */
@RestController
@RequestMapping("/quota/dimensionDetail")
@Api(tags = "维度编码详情")
public class QuotaDimensionDetailController extends ApiController {
    @Autowired
    IQuotaDimensionDetailService quotaDimensionDetailService;
    @Autowired
    ColnameAliasService colnameAliasService;
    @Autowired
    DatasourceQueryService datasourceQueryService;
    @Autowired
    TablenameAliasService tablenameAliasService;

    @Autowired
    IQuotaDimensionService quotaDimensionService;

    /**
     * 分页查询所有数据
     */
    @GetMapping("/list")
    @ApiOperation("分页查询所有数据")
    @ApiImplicitParams(
            {@ApiImplicitParam(paramType = "query", dataType = "String", name = "current", value = "当前页", defaultValue = "1", required = true),
                    @ApiImplicitParam(paramType = "query", dataType = "String", name = "size", value = "一页大小", defaultValue = "10", required = true),
                    @ApiImplicitParam(paramType = "query", dataType = "Boolean", name = "ifCount", value = "是否查询总数", defaultValue = "true"),
                    @ApiImplicitParam(paramType = "query", dataType = "String", name = "ascs", value = "升序字段，多个用逗号分隔"),
                    @ApiImplicitParam(paramType = "query", dataType = "String", name = "descs", value = "降序字段，多个用逗号分隔")
            })
    public R<IPage<DimensionVo>> selectAll() {
        BaseForm form = new BaseForm();
        QueryWrapper<QuotaDimensionDetail> query = (QueryWrapper<QuotaDimensionDetail>) form.pageQueryWrapperCustom(
                form.getParameters(), new QueryWrapper<QuotaDimensionDetail>());
        return success(quotaDimensionDetailService.page(form.getPlusPagingQueryEntity(), query));
    }


    /**
     * 获取详细信息
     */
    @ApiOperation("获取详细信息")
    @GetMapping(value = "{id}")
    public R<QuotaDimensionDetail> getInfo(@PathVariable Serializable id) {
        return success(quotaDimensionDetailService.getById(id));
    }

    /**
     * 新增维度详细信息
     */
    @ApiOperation("新增维度")
    @PreAuthorize("@ss.hasPermi('quota:dimensionDetail:add')")
    @PostMapping
    public R<Boolean> add(@RequestBody QuotaDimensionDetail quotaDimensionDetail) {
        return success(quotaDimensionDetailService.save(quotaDimensionDetail));
    }

    @ApiOperation("批量新增维度")
    @PreAuthorize("@ss.hasPermi('quota:dimensionDetail:add')")
    @PostMapping("/batchAdd")
    public R<Boolean> batchAdd(@RequestBody List<QuotaDimensionDetail> quotaDimensionDetails) {
        return success(quotaDimensionDetailService.saveBatch(quotaDimensionDetails));
    }

    /**
     * 删除维度详细信息
     */
    @ApiOperation("删除维度详细信息")
    @PreAuthorize("@ss.hasPermi('quota:dimensionDetail:remove')")
    @Log(title = "删除维度详细信息", businessType = BusinessType.DELETE)
    @DeleteMapping
    public R<Boolean> remove(@RequestParam("idList") List<Integer> ids) {
        return success(quotaDimensionDetailService.removeByIds(ids));
    }

    /**
     * 获取维度详情列表
     */
    @ApiOperation("获取维度详情列表")
    @PreAuthorize("@ss.hasPermi('quota:dimensionDetail:list')")
    @GetMapping
    public R<List<DimensionVo>> selectDimensionDetail(@RequestBody DimensionVo vo) {
        return success(quotaDimensionDetailService.selectDimensionDetail(vo));
    }

    /**
     * 根据字段别名标识获取字段所有的distinct value
     */
    @GetMapping("/columnValue")
    @ApiOperation("获取字段唯一值")
    public R<List<String>> getDistinctColumnValue(Integer datasourceId, Integer colnameAliasId) {
        ColnameAlias ca = colnameAliasService.getById(colnameAliasId);
        if (ca != null) {
            TablenameAlias ta = tablenameAliasService.getById(ca.getTablenameAliasId());
            if (ta != null)
                return success(datasourceQueryService.getDistinctColumnValue(datasourceId, ta.getTableName(), ca.getColumnName()));
        }
        return failed("查询失败");
    }

    @PostMapping("/detail")
    @ApiOperation(("根据字段别名id查询维度详情记录"))
    public R<List<DimensionVo>> selectColumnDimenstionDetail(@RequestBody DimensionVo vo) {
        return success(quotaDimensionDetailService.selectColumnDimenstionDetail(vo));
    }

    @GetMapping("/delete")
    @ApiOperation("删除维度明细")
    public R<Boolean> remove(@RequestParam("id") Integer id) {
        return success(quotaDimensionDetailService.removeById(id));
    }

    @PostMapping("/addDetail")
    @ApiOperation("添加维度详情")
    public R<Integer> addDetail(@RequestBody DimensionVo vo) {
        Integer detailId = -1;
        try {
            Integer dimensionId = vo.getDimensionId();
            if (null == dimensionId || "".equals(dimensionId)) {
                QuotaDimension dim = new QuotaDimension();
                dim.setComments(vo.getComment());
                dim.setDimensionAttr(vo.getDimensionAttr());
                dim.setDimensionCode(vo.getDimensionCode());
                dim.setDimensionName(vo.getDimensionName());
                dim.setDimensionCode(vo.getDimensionCode());
                dim.setDimensionType(vo.getDimensionType());
                dim.setUpdateBy(vo.getUpdateBy());
                dim.setUpdateDate(new Date());
                dim.setActiveYear(vo.getActiveYear());
                dim.setUpperId(vo.getUpperId());
                dim.setStatus(vo.getStatus());
                if (quotaDimensionService.save(dim))
                    dimensionId = dim.getId();

            }
            if (null != dimensionId && dimensionId > 1) {
                QueryWrapper<QuotaDimensionDetail> query = new QueryWrapper<QuotaDimensionDetail>().
                        eq("DIMENSION_ID", dimensionId).
                        eq("COLNAME_ID", vo.getColnameId());

                int count = quotaDimensionDetailService.count(query);
                if (count > 0) {
                    return failed("记录已存在，请刷新后重试");
                }
                QuotaDimensionDetail dd = new QuotaDimensionDetail();
                dd.setCodeValue(vo.getCodeValue());
                dd.setColnameId(vo.getColnameId());
                dd.setDimensionId(dimensionId);
                dd.setUpdateDate(new Date());
                if (quotaDimensionDetailService.save(dd))
                    vo.setDimensionDetailId(dd.getDimensionId());

            }
        } catch (Exception e) {
            return failed(e.getMessage());
        }
        return success(vo.getDimensionDetailId());
    }
}
